package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"logi-deliv/cache"
	"logi-deliv/model"
	"time"
)

func PeopleAdd(c *gin.Context) {
	people_code := c.PostForm("people_code")
	name := c.PostForm("name")
	address := c.PostForm("address")
	tel := c.PostForm("tel")
	status := c.PostForm("status")
	data := model.People{
		PeopleCode: people_code,
		Name:       name,
		Address:    address,
		Tel:        tel,
		Status:     status,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
	})
	return
}
func OrderAdd(c *gin.Context) {
	order_code := c.PostForm("order_code")
	order_address := c.PostForm("order_address")
	data := model.Order{
		OrderCode:    order_code,
		OrderAddress: order_address,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
	})
	return
}

func PeopleOrderList(c *gin.Context) {

	var peopleList []model.PeopleOrderList
	redis_key := "people_order_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("orders").Select(
			"orders.id as OrderId",
			"orders.order_code as OrderCode",
			"orders.order_address as OrderCode",
			"peoples.people_code as PeopleCode",
			"peoples.name as Name",
			"peoples.address as Address",
			"peoples.tel as Tel",
			"peoples.status as Status",
		).Joins("LEFT JOIN peoples on orders.pid=peoples.id").Debug().Find(&peopleList)
		jsonData, _ := json.Marshal(peopleList)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &peopleList)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": peopleList,
	})
	return
}

func PeopleOrderDetail(c *gin.Context) {
	id := c.Query("id")
	var peopleList model.PeopleOrderList
	redis_key := "people_order_detail"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("orders").Select(
			"orders.id as OrderId",
			"orders.order_code as OrderCode",
			"orders.order_address as OrderCode",
			"peoples.people_code as PeopleCode",
			"peoples.name as Name",
			"peoples.address as Address",
			"peoples.tel as Tel",
			"peoples.status as Status",
		).Joins("LEFT JOIN peoples on orders.pid=peoples.id").
			Where("orders.id=?", id).Debug().Find(&peopleList)
		jsonData, _ := json.Marshal(peopleList)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &peopleList)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": peopleList,
	})
	return
}
